package com.ruoyi.cart.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.order.domain.Order;
import com.ruoyi.order.mapper.OrderMapper;
import com.ruoyi.product.domain.Product;
import com.ruoyi.product.mapper.ProductMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.cart.mapper.CartMapper;
import com.ruoyi.cart.domain.Cart;
import com.ruoyi.cart.service.ICartService;

/**
 * 购物车Service业务层处理
 * 
 * @author wxl
 * @date 2023-11-11
 */
@Service
public class CartServiceImpl implements ICartService 
{
    @Autowired
    private CartMapper cartMapper;

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private OrderMapper orderMapper;

    /**
     * 查询购物车
     * 
     * @param cartId 购物车主键
     * @return 购物车
     */
    @Override
    public Cart selectCartByCartId(Long cartId)
    {
        return cartMapper.selectCartByCartId(cartId);
    }

    /**
     * 查询购物车列表
     * 
     * @param cart 购物车
     * @return 购物车
     */
    @Override
    public List<Cart> selectCartList(Cart cart)
    {
        Long userId = SecurityUtils.getLoginUser().getUserId();
        cart.setCustomerId(userId);
        return cartMapper.selectCartList(cart);
    }

    /**
     * 新增购物车
     * 
     * @param cart 购物车
     * @return 结果
     */
    @Override
    public int insertCart(Cart cart)
    {
        Long userId = SecurityUtils.getLoginUser().getUserId();
        cart.setCustomerId(userId);
        return cartMapper.insertCart(cart);
    }

    /**
     * 修改购物车
     * 
     * @param cart 购物车
     * @return 结果
     */
    @Override
    public int updateCart(Cart cart)
    {
        return cartMapper.updateCart(cart);
    }

    /**
     * 批量删除购物车
     * 
     * @param cartIds 需要删除的购物车主键
     * @return 结果
     */
    @Override
    public int deleteCartByCartIds(Long[] cartIds)
    {
        return cartMapper.deleteCartByCartIds(cartIds);
    }

    /**
     * 删除购物车信息
     * 
     * @param cartId 购物车主键
     * @return 结果
     */
    @Override
    public int deleteCartByCartId(Long cartId)
    {
        return cartMapper.deleteCartByCartId(cartId);
    }

    /**
     * 提交下单
     * @param cartIds
     * @return
     */
    @Override
    public AjaxResult orderByCartIds(Long[] cartIds) {
        Long userId = SecurityUtils.getLoginUser().getUserId();
        BigDecimal totalAmount = BigDecimal.ZERO;
        StringBuilder remarkBuilder = new StringBuilder();
        List<String> lowStockProducts = new ArrayList<>();

        for (Long cartId : cartIds) {
            Cart cart = cartMapper.selectCartByCartId(cartId);
            if (cart != null) {
                Product product = productMapper.selectProductByProductId(cart.getProductId());
                if (product.getQuantity() < cart.getQuantity()) {
                    lowStockProducts.add(product.getName() + " 库存不足");
                    continue;
                }
                BigDecimal itemTotal = cart.getTotalPrice();
                totalAmount = totalAmount.add(itemTotal);
                remarkBuilder.append(cart.getProductName())
                        .append(" x ")
                        .append(cart.getQuantity())
                        .append("; ");
            }
        }

        if (!lowStockProducts.isEmpty()) {
            // 库存不足，无法下单
            return AjaxResult.error("以下产品库存不足: " + String.join(", ", lowStockProducts));
        }

        // 所有商品库存充足，减少库存并创建订单
        for (Long cartId : cartIds) {
            Cart cart = cartMapper.selectCartByCartId(cartId);
            productMapper.decreaseStock(cart.getProductId(), cart.getQuantity());
        }

        // 创建订单对象
        Order order = new Order();
        order.setCustomerId(userId);
        order.setOrderDate(DateUtils.getNowDate());
        order.setStatus("0"); // 下单
        order.setTotalPrice(totalAmount);
        order.setRemark(remarkBuilder.toString());
        orderMapper.insertOrder(order);
        deleteCartByCartIds(cartIds);
        return AjaxResult.success();
    }

}
